//引入mongoose
// const {Schema, model} = require('mongoose');
 
//引入model
//引入model 一定要解构来引入 
const {studentsModel} = require('./models/studentsModel');
//studentsModel={name,age,gender,classId,imagesName}

 
//获取学生数据
module.exports.getStudents = async params => {   
    // params = {currentPage,pageSize,totalPage,totalStudent,searchValue}

    const {currentPage,pageSize} = params;

    //.populate() 嵌套关联数据表查询
    //studentsModel={name,age,gender,classId}

    //获取学生总条数
    const totalStudent = await studentsModel.countDocuments();

    //计数页数
    const totalPage = Math.ceil(totalStudent / pageSize);


    //关联查询 班级，教师
    const students = await studentsModel
    .find()
    .populate({
        path:'classId',
        populate:{
            path:'teachers'
        }
    })
    .limit(pageSize - 0)  // 设置请求数据的条数  "- 0" 是转换字符串为数值
    .skip((currentPage - 1) * pageSize)  // 设置跳过数据的条数;

    return {totalStudent,totalPage,students};
}

//搜索学生
module.exports.searchStudents = async params =>{
    //params = {
    // searchType,
    // searchValue,
    // currentPage,pageSize,totalPage,totalStudent}

    const {searchType:type,searchValue:value,currentPage,pageSize} = params;

    //符合条件的学生数
    const totalStudent = await studentsModel.countDocuments({
        [type]: { $regex: value, $options: '$i' }
    });
    // 计算总页数
    const totalPage = Math.ceil(totalStudent / pageSize);

    //搜索也要关联查询
    const students = await studentsModel
    .find({
        //正则实现模糊查询，option不区分大小写
        [type]:{$regex: value, $options: '$i'}
    })
    .populate({
        path:'classId',
        populate:{
            path:'teachers'
        }
    })
    .limit(pageSize - 0)  // 设置请求数据的条数  "- 0" 是转换字符串为数值
    .skip((currentPage - 1) * pageSize)  // 设置跳过数据的条数;

    return {totalStudent,totalPage,students};    
}

//新增学生
module.exports.addStudent = async params =>{
    //目前:params{name,age,gender,classId}

    const result = await studentsModel.create(params);    
    return result;
}

//修改学生--通过_id获取学生信息
module.exports.upgradeGetStudent = async params =>{
    const result = await studentsModel.findById(params._id);
    return result;
}

//修改学生
module.exports.upgradeStuInfo = async params =>{
    const {_id,name,age,gender,classId,imagesName} = params
    const result = await studentsModel.updateOne({_id},{
        name,
        age,
        gender,
        classId,
        imagesName
    });
    return result;
}

//删除学生
module.exports.deleteStudent = async ({..._id}) =>{
    const result = await studentsModel.deleteOne({_id});
    return result;
}